package com.aldobucchi.x.flash.display.BitmapData
{
	
	
	import flash.display.BitmapData;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	
	
	public class FloodCluster
	{
		
		
		public var owner:FloodSelector;
		
		public var color:uint;
		
		
		
		private var _boundingRect:Rectangle;
		
		public function get boundingRect( ):Rectangle
		{
			if ( !_boundingRect )
			{
				_boundingRect = sourceBD.getColorBoundsRect( 0xFFFFFFFF, color );
			}
			return _boundingRect;
		}
		
		
		
		
		private var _referencePoint:Point;
		
		public function get referencePoint( ):Point
		{
		
			if ( ! _referencePoint )
			{
				// test points within bounds
				
				var x:int, y:int, p:Point;

				for ( x=boundingRect.topLeft.x; x<=boundingRect.bottomRight.x; x++ )
				{
					for ( y=boundingRect.topLeft.y; y<=boundingRect.bottomRight.y; y++ )
					{
						p = new Point( x, y );	
						if ( owner.getClusterAtPoint( p ) == this )
						{
							_referencePoint = p;
							return p;
						}					
					}			
				}			

			
			}

			return _referencePoint;
		}
		
		
		
		
		
		
		
		

		// encapsulated here to aid refactoring
		private function get sourceBD( ):BitmapData
		{
			return owner.bd; 
		}
		
		
		
		
		
		
		
		
		public function FloodCluster( owner:FloodSelector, color:uint  )
		{
			this.owner = owner;
			this.color = color;
		}
		
		
		
		
		public function draw( target:BitmapData, color:uint=0xffff0000, destPoint:Point=null ):void
		{
			if ( destPoint == null )
				destPoint = new Point( );
				
			target.threshold( sourceBD, boundingRect, destPoint, "==", this.color, color );	
		
		}
		
		
		
		

	}
	
}
